import jwt
from datetime import datetime, timedelta, timezone
from typing import Annotated, Optional
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends, HTTPException, status
from jwt import InvalidTokenError
import redis
from config.settings import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES  # 从配置导入

redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/user/login/account")  # 匹配实际登录接口路径


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)  # 使用配置的默认时间
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


async def verify_token(token: str, return_payload: bool = False) -> str | dict:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    if redis_client.exists(f"blacklist:{token}"):
        raise credentials_exception
    try:
        print("token:!!!!!!", token)
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        print("payload:!!!!!!", payload)
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        if return_payload:
            return payload  # 返回完整payload
        return username
    except jwt.InvalidTokenError:
        raise credentials_exception